/*
 * Copyright (c) 2009, Hamish Morgan
 * All rights reserver.
 */
package locusts.common.behaviours;

import java.util.List;

import javax.vecmath.Vector2d;

import locusts.common.entities.Flock;
import locusts.common.entities.Vehicle;

/**
 * Steering to stay close to neighbouring boids.
 * 
 * @author Hamish Morgan
 */
public class FlockCohesionBehaviour extends AbstractFlockBehaviour {
    
    public FlockCohesionBehaviour(double weight, Flock boids,
            double minDistance, double maxDistance, double maxAngle) {
        super(weight, boids, minDistance, maxDistance, maxAngle);
    }
    
    // Cohesion: steer to move toward the centre of mass of the local
    // flockmates
    public Vector2d getSteering(final Vehicle boid) {
        
        final Vector2d steering = new Vector2d();
        List<Vehicle> neighbors = getNeighbors(boid);
        
        if (neighbors.size() == 0)
            return steering;
        if (getWeight() == 0d)
            return steering;
        
        for (Vehicle other : neighbors)
            steering.add(other.position);
        
        steering.scale(1d / neighbors.size());
        steering.sub(boid.position);
        
        steering.scale(getWeight());
        return steering;
    }
}